/*
 * LightSensor.java
 *
 * Created on June 16, 2007, 7:47 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */
package atag.runtime.sensors;

import java.nio.ByteBuffer;
import java.util.List;
import javax.smartcardio.Card;
import javax.smartcardio.CardChannel;
import javax.smartcardio.CardException;
import javax.smartcardio.CardTerminal;
import javax.smartcardio.TerminalFactory;

/**
 * Represents an RFID Samert Card Reader.
 * @author ajay chhatwal
 */
public class RFIDSensor {

    CardTerminal terminal = null;

    /**
     * Creates a new instance of RFIDSensor
     * @param name The name of the RFID Card Reader
     * @throws CardException if error occurs during communication with the Smart
     * Card Reader
     */
    public RFIDSensor(String name) throws CardException {
        // Get reference to our terminal
        TerminalFactory factory = TerminalFactory.getDefault();
        List<CardTerminal> terminals = factory.terminals().list();
        String readerName = "";
        for (int i = 0; i < terminals.size(); i++) {
            readerName = terminals.get(i).getName();
            //  System.out.println(readerName);
            if (readerName.equalsIgnoreCase(name)) {
                terminal = terminals.get(i);
            }
        }
        if (terminal == null) {
            System.err.println("Specified Card Reader "+name+" Not Found");
            throw new CardException("Specified Card Reader "+name+" Not Found");
        }
    }

    /**
     * Waits for an RFID card to be swiped (touched and removed) and returns its
     * Unique Identifier (UID)
     * @return the UID of the card
     * @throws CardException if error occurs during communication with the Smart
     * Card stack or the card itself.
     */
    public String getUID() throws CardException {
        // System.out.println("Waiting for a card..");
        terminal.waitForCardPresent(0);

        Card card = terminal.connect("*");
        CardChannel channel = card.getBasicChannel();

        // Read UID of the card


        byte[] baReadUID = new byte[5];

        baReadUID = new byte[]{(byte) 0xFF, (byte) 0xCA, (byte) 0x00,
                    (byte) 0x00, (byte) 0x00};

        String rfid = send(baReadUID, channel);
        terminal.waitForCardAbsent(0);


        return rfid;


    }

    private String send(byte[] cmd, CardChannel channel) throws CardException {

        String res = "";



        byte[] baResp = new byte[258];
        ByteBuffer bufCmd = ByteBuffer.wrap(cmd);
        ByteBuffer bufResp = ByteBuffer.wrap(baResp);

        // output = The length of the received response APDU


        int output = 0;
        output = channel.transmit(bufCmd, bufResp);



        for (int i = 0; i
                < output; i++) {
            res += String.format("%02X", baResp[i]);
            // The result is formatted as a hexadecimal integer


        }

        return res;

    }
}
